#include "doorbell_button.h"
#include <iot_button.h>
#include "doorbell_codec.h"
#include "doorbell_mqtt.h"

static button_handle_t button = NULL;
static doorbell_button_cb short_press_cb = NULL;
static void *short_press_arg = NULL;
static doorbell_button_cb long_press_cb = NULL;
static void *long_press_arg = NULL;

extern const uint8_t dingdong_start[] asm("_binary_output_pcm_start");
extern const uint8_t dingdong_end[] asm("_binary_output_pcm_end");

static void doorbell_button_internal_callback(void *button_handle, void *usr_data)
{
    button_event_t event = iot_button_get_event(button_handle);
    switch (event)
    {
    case BUTTON_SINGLE_CLICK:
        doorbell_mqtt_publish("{\"data\":\"dingdong\"}", 19);
        doorbell_codec_play(dingdong_start, dingdong_end - dingdong_start);
        break;
    case BUTTON_LONG_PRESS_START:
        if (long_press_cb)
        {
            long_press_cb(long_press_arg);
        }
        break;
    default:
        break;
    }
}

void doorbell_button_init()
{
    button_config_t config = {
        .type = BUTTON_TYPE_GPIO,
        .short_press_time = 100,
        .long_press_time = 750,
        .gpio_button_config = {
            .gpio_num = BUTTON_PIN,
            .active_level = 1,
            .enable_power_save = true,
        },
    };
    button = iot_button_create(&config);
    assert(button);
    ESP_ERROR_CHECK(iot_button_register_cb(button, BUTTON_SINGLE_CLICK, doorbell_button_internal_callback, NULL));
    ESP_ERROR_CHECK(iot_button_register_cb(button, BUTTON_LONG_PRESS_START, doorbell_button_internal_callback, NULL));
}

void doorbell_button_long_press_cb(doorbell_button_cb cb, void *arg)
{
    long_press_cb = cb;
    long_press_arg = arg;
}

void doorbell_button_deinit()
{
    ESP_ERROR_CHECK(iot_button_delete(button));
}
